package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.KnowledgeAnnounceList.KnowledgeAnnounceDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 公告详情、修改
 *
 * @author wu
 */
public class PublishAnnounceDetailFragment extends PublishAnnounceBaseFragment {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";
  KnowledgeAnnounceDetail mDetail;

  protected String mId;// 主键
  protected String mAnnounceType;// 公文类别
  protected String mAnnounceTypeCode;// 公文类别编码
  protected String mKeyWords;// 关键字
  protected String mTitle;// 标题
  protected String mFile;// 附件
  protected String mBeginDate;// 起始时间
  protected String mEndDate;// 结束时间
  protected String mContent;// 内容简介
  protected String mRemark;// 默认备注字段

  protected String mRegStaffName;// 创建人
  protected String mRegStaffId;// 创建人code
  protected String mRegDate;// 创建时间
  protected String mRegDepartment;// 创建部门
  protected String mRegDepartmentCode;// 创建部门code
  protected String mCheckStaffId;// 审核人ID
  protected String mCheckStaffName;// 审核人姓名
  protected String mCheckDate;// 审核日期

  protected String mOrderNo;// 默认排序字段
  protected String mMemberCode;// 会员编码
  protected String mMemberName;// 所属会员名称
  protected String mRunId;// 流程实例runId
  protected String mIfRemindReader;// 是否提示阅读人
  protected String mDocKnowledgeNo;// 公文编号
  protected String mDataStatus;// 数据状态
  protected String mSystemIndex;
  protected String mFileOriginalName;// 用户上传时设置的文件名称

  private BaseVolleyActivity mActicity;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 设置返回图标
    setTitleCustom(R.string.announceDtail);
    mDetail = (KnowledgeAnnounceDetail) getArguments().getSerializable(EXTRA_VALUE);
    if (mDetail != null) {
      mId = mDetail.getId();
      mAnnounceType = mDetail.getDocKindName();
      mAnnounceTypeCode = mDetail.getDocKindCode();
      mKeyWords = mDetail.getDocKeyWords();
      mTitle = mDetail.getNoticeTitle();
      mFile = mDetail.getFilePath();
      mBeginDate = mDetail.getNoticeBegin();
      mEndDate = mDetail.getNoticeEnd();
      mContent = mDetail.getDocContentDesc();
      mRemark = mDetail.getRemark();// 默认备注字段

      mRegStaffName = mDetail.getRegStaffName();
      mRegStaffId = mDetail.getRegStaffId();
      mRegDate = mDetail.getRegDate();// 登记时间
      mRegDepartment = mDetail.getRegDeptName();
      mRegDepartmentCode = mDetail.getRegDeptCode();
      mCheckStaffId = mDetail.getCheckStaffId();// 审核人ID
      mCheckStaffName = mDetail.getCheckStaffName();// 审核人姓名
      mCheckDate = mDetail.getCheckDate();// 审核日期

      mOrderNo = mDetail.getOrderNo();// 默认排序字段
      mMemberCode = mDetail.getMemberCode();// 会员编码
      mMemberName = mDetail.getMemberName();
      mRunId = mDetail.getRunId();
      mIfRemindReader = mDetail.getIfRemindReader();
      mDocKnowledgeNo = mDetail.getDocKnowledgeNo();
      mDataStatus = mDetail.getDataStatus();
      mFileOriginalName = mDetail.getFileOriginalName();
      mSystemIndex = mDetail.getSystemIndex();
    }

    mActicity = (BaseVolleyActivity) getActivity();
    mActicity.invalidateOptionsMenu();
  }

  protected void initView() {
    getNotEdit();

    if (!TextUtils.isEmpty(mAnnounceType)) {
      mtvAnnounceTypePublicAnnounce.setTextContent(mAnnounceType);
    }

    if (!TextUtils.isEmpty(mKeyWords)) {
      mtvKeyWordsDetailPublicAnnounce.setTextContent(mKeyWords);
    }

    if (!TextUtils.isEmpty(mTitle)) {
      mtv_announceTitle.setTextContent(mTitle);
    }

    if (!TextUtils.isEmpty(mRemark)) {
      mtvOhtersRemark.setTextContent(mRemark);
    }

    if (!TextUtils.isEmpty(mFileOriginalName)) {
      if ("(null)".equalsIgnoreCase(mFileOriginalName)) {
        mtv_addFileAnnounce.setTextContent("");
      } else {
        mtv_addFileAnnounce.setTextContent(mFileOriginalName);
      }
    }

    if (!TextUtils.isEmpty(mRegStaffName)) {
      mtv_registerAnnounce.setTextContent(mRegStaffName);
    }
    if (!TextUtils.isEmpty(mRegDate)) {
      mtv_registerTimeAnnounce.setTextContent(mRegDate);
    }
    if (!TextUtils.isEmpty(mRegDepartment)) {
      mtv_registerDepartment.setTextContent(mRegDepartment);
    }

    mtv_announceIntroduction.setVisibility(View.GONE);
    rlWebViewHolder.setVisibility(View.VISIBLE);
    //图文混排
    String content = MyUtils.parseWebImage(mContent);//图片自适应
    mwv_announceDetail.loadDataWithBaseURL(ApiConst.getUrlMain(), content, "text/html", "utf-8",
        null);//图文混排
  }

  private void getNotEdit() {
    mtvAnnounceTypePublicAnnounce.setInputEnabled(false);
    mtvKeyWordsDetailPublicAnnounce.setInputEnabled(false);
    mtv_announceTitle.setInputEnabled(false);
    mtvOhtersRemark.setInputEnabled(false);
    //        mtv_beginDate.setInputEnabled(false);
    //        mtv_endDate.setInputEnabled(false);
    mtv_addFileAnnounce.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (mDetail == null || MyStringUtil.isEmpty(mDetail.getFilePath())) return;
        showDialog(ExtraDownLoadDialogFragment.newInstance("", mDetail.getFilePath()), 0);
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if ("new".equalsIgnoreCase(mDataStatus) || "abort".equalsIgnoreCase(mDataStatus)) {
      inflater.inflate(R.menu.menu_alter_submit_delete, menu);
    } else if ("waitCheck".equalsIgnoreCase(mDataStatus)) {
      inflater.inflate(R.menu.menu_stop, menu);
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  public static Fragment newInstance(KnowledgeAnnounceDetail detail) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, detail);
    PublishAnnounceDetailFragment fragment = new PublishAnnounceDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override // 响应返回图标
  public boolean onOptionsItemSelected(MenuItem item) {
    AlertDialog.Builder dialog;
    switch (item.getItemId()) {

      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_alter:
        if (!TextUtils.isEmpty(mDataStatus)) {
          if ("new".equalsIgnoreCase(mDataStatus) || "abort".equalsIgnoreCase(mDataStatus)) {
            Intent intent = new Intent(getActivity(), PublishAccounceEditActivity.class);
            intent.putExtra(PublishAccounceEditFragment.EXTRA_VALUE, mDetail);
            startActivity(intent);
          } else {
            ToastUtil.show(R.string.onlyNewOrBackEdit);
          }
        }

        break;

      case R.id.menu_item_submit:
        if (!TextUtils.isEmpty(mMemberName)) {
          ToastUtil.show(R.string.noFlow);
        } else {
          dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.ifSureStart);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostSubmit();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;

      case R.id.menu_item_delete:
        dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.deleteMind);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            vollyPostDelete();
          }
        });

        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();
        break;
      case R.id.menu_item_stop:
        vollyePostStop();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 终止流程
   */
  private void vollyePostStop() {
    MyUtils.showDialogLoading(getActivity(), R.string.interrupting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    params.put("runId", mRunId);// 数据状态
    mActicity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.interruptFail);
        LogUtil.e("arg0===" + arg0);
      }
    });
    LogUtil.e("params===" + params);
  }

  /**
   * 启动流程
   */
  private void volleyPostSubmit() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ANNOUNCE_START);
    HashMap<String, String> params = new HashMap<>();
    params.put("isList", "1");
    params.put("id", mId);
    mActicity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.startFolwFail);
        LogUtil.e("arg0===" + arg0);
      }
    });
    LogUtil.e("params===" + params);
  }

  /**
   * 删除
   */
  private void vollyPostDelete() {
    MyUtils.showDialogLoading(getActivity(), R.string.deleting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_ANNOUNCE);
    HashMap<String, String> params = new HashMap<>();
    params.put("type", "mobile");
    params.put("id", mId);
    mActicity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.deleteFail);
        LogUtil.e("arg0===" + arg0);
      }
    });
    LogUtil.e("params===" + params);
  }
}
